package com.xinqi.modules.prepare.question.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinqi.common.core.utils.StringUtils;
import com.xinqi.common.base.dto.CommonFileDTO;
import com.xinqi.common.base.dto.QuestionOptionsDTO;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.response.PageInfo;
import com.xinqi.common.base.response.Param;
import com.xinqi.common.base.utils.json.JSON;
import com.xinqi.common.mybatis.utils.Pages;
import com.xinqi.common.mybatis.utils.Queries;
import com.xinqi.modules.prepare.question.convert.PrepareQuestionFolderRefConvert;
import com.xinqi.modules.prepare.question.domain.PrepareQuestionFolderRefEntity;
import com.xinqi.modules.prepare.question.dto.req.PrepareQuestionFolderRefCreateDTO;
import com.xinqi.modules.prepare.question.dto.req.PrepareQuestionFolderRefDeleteDTO;
import com.xinqi.modules.prepare.question.dto.req.PrepareQuestionFolderRefQueryDTO;
import com.xinqi.modules.prepare.question.dto.req.PrepareQuestionFolderRefUpdateDTO;
import com.xinqi.modules.prepare.question.dto.rsp.PrepareQuestionBankResultDTO;
import com.xinqi.modules.prepare.question.dto.rsp.PrepareQuestionFolderRefResultDTO;
import com.xinqi.modules.prepare.question.dto.rsp.PrepareQuestionStatsDataDTO;
import com.xinqi.modules.prepare.question.manager.PrepareQuestionFolderRefManager;
import com.xinqi.modules.prepare.question.service.PrepareQuestionFolderRefService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

;

/**
 * 备课区试题夹关联题目服务层实现
 *
 * @author: system
 * @date: 2023/03/19
 */
@Validated
@Service("prepareQuestionFolderRefService")
@RequiredArgsConstructor
public class PrepareQuestionFolderRefServiceImpl implements PrepareQuestionFolderRefService {
    private final PrepareQuestionFolderRefConvert prepareQuestionFolderRefConvert;
    private final PrepareQuestionFolderRefManager prepareQuestionFolderRefManager;

    /**
     * 分页查询 备课区试题夹关联题目数据
     */
    @Override
    @DS("slaver")
    public PageInfo<PrepareQuestionFolderRefResultDTO> page(Param pageable, PrepareQuestionFolderRefQueryDTO query) {
        IPage<PrepareQuestionFolderRefEntity> page = prepareQuestionFolderRefManager.page(Pages.page(pageable), wrapper(query));
        return Pages.convert(page, prepareQuestionFolderRefConvert::convert);
    }

    @Override
    @DS("slaver")
    public PageInfo<PrepareQuestionBankResultDTO> questionPage(PrepareQuestionFolderRefQueryDTO dto) {
        Page<Object> page1 = Pages.page(dto);
        // 不查询总数
//        page1.setSearchCount(false);
        IPage<PrepareQuestionBankResultDTO> page = prepareQuestionFolderRefManager.questionPage(page1, dto);

        return Pages.convert(page.setRecords(setPropertiesList(page.getRecords())));
    }

    @Override
    public PrepareQuestionStatsDataDTO questionStats(Long prepareId, Long questionFolderId) {
        return prepareQuestionFolderRefManager.questionStats(prepareId, questionFolderId);
    }

    /**
     * 查询 备课区试题夹关联题目数据
     */
    @Override
    public List<PrepareQuestionFolderRefResultDTO> find(PrepareQuestionFolderRefQueryDTO query) {
        return prepareQuestionFolderRefManager.list(wrapper(query)).stream().map(prepareQuestionFolderRefConvert::convert).collect(Collectors.toList());
    }

    private LambdaQueryWrapper<PrepareQuestionFolderRefEntity> wrapper(PrepareQuestionFolderRefQueryDTO query) {
        LambdaQueryWrapper<PrepareQuestionFolderRefEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(PrepareQuestionFolderRefEntity::getId, v));
        return wrapper;
    }

    /**
     * 根据id查询 备课区试题夹关联题目数据
     */
    @Override
    public PrepareQuestionFolderRefResultDTO findById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return Optional.ofNullable(prepareQuestionFolderRefManager.findById(id)).map(prepareQuestionFolderRefConvert::convert).orElse(null);
    }

    /**
     * 新增 备课区试题夹关联题目数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(@Valid PrepareQuestionFolderRefCreateDTO dto) {
        PrepareQuestionFolderRefEntity entity = prepareQuestionFolderRefConvert.create(dto);
        prepareQuestionFolderRefManager.save(entity);
        return entity.getId();
    }

    /**
     * 根据id修改 备课区试题夹关联题目数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(@Valid PrepareQuestionFolderRefUpdateDTO dto) {
        PrepareQuestionFolderRefEntity old = Optional.ofNullable(prepareQuestionFolderRefManager.getById(dto.getId())).orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("数据不存在"));
        PrepareQuestionFolderRefEntity entity = prepareQuestionFolderRefConvert.update(dto);
        return prepareQuestionFolderRefManager.updateById(entity);
    }

    /**
     * 根据id删除 备课区试题夹关联题目数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return prepareQuestionFolderRefManager.removeById(id);
    }

    /**
     * 根据id删除 备课区试题夹关联题目数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(PrepareQuestionFolderRefDeleteDTO dto) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(dto.getId()), "ID不能为空");
        return prepareQuestionFolderRefManager.deleteById(dto.getId());
    }

    /**
     * jsonString转List,由于直接查出来的是DTO，而dto被别的接口用了，所以这里使用手动转换的方式
     */
    private List<PrepareQuestionBankResultDTO> setPropertiesList(List<PrepareQuestionBankResultDTO> records) {
        if (CollectionUtils.isEmpty(records)) {
            return records;
        }
        records = records.stream().peek(r -> {
            //选项
            if (StringUtils.isNotEmpty(r.getOptions())) {
                r.setOptionList(JSON.parseList(r.getOptions(), QuestionOptionsDTO.class));
            }

            //题目文件
            if (StringUtils.isNotEmpty(r.getQuestionFile())) {
                r.setQuestionFiles(JSON.parseList(r.getQuestionFile(), CommonFileDTO.class));
            }

            //解析文件
            if (StringUtils.isNotEmpty(r.getAnalysisFile())) {
                r.setAnalysisFiles(JSON.parseList(r.getAnalysisFile(), CommonFileDTO.class));
            }

            //答案文件
            if (StringUtils.isNotEmpty(r.getAnswerFile())) {
                r.setAnswerFiles(JSON.parseList(r.getAnswerFile(), CommonFileDTO.class));
            }
        }).collect(Collectors.toList());

        return records;
    }

}
